package edu.vt.ece.rt.dstm;

import java.util.concurrent.ConcurrentHashMap;

/*
 * To Support different Context types in future
 * @author Sudhanshu
 * TODO: Remove the context after commit or abort
 */
public class ContextDelegator {
	/*
	 * Allow application to access the different Context Locally
	 */
	public static ConcurrentHashMap<Long, Context>	contextMap = new ConcurrentHashMap<Long, Context>();
	
//	final private static ContextThreadLocal THREAD_CONTEXT = new ContextThreadLocal();
//
//	private static class ContextThreadLocal extends ThreadLocal<Context>
//	{
//		private Class<?> contextClass;  
//
//		public ContextThreadLocal(){
//			try {
//				this.contextClass = Class.forName(Names.ContextClass);
//				return;
//			} catch (ClassNotFoundException e) {
//				e.printStackTrace(); // TODO add logger
//			}
//		}
//
//		@Override
//		protected synchronized Context initialValue() {
//			try {
//				return (Context)this.contextClass.newInstance();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			return null;
//		}
//	}

	public static Context getContext(){
	    return new Context();
	}

	
	public static Context getContext(Long txnId){
		Context c;
		if((c=contextMap.get(txnId)) != null){		//Check if local
//			Logger.debug(" Read txn "+c.getContextId()+" status "+c.getStatus());
			return c;
		}
		
		//Create new Context if required
		c = new Context(txnId);
		c.register();
		return c;
	}
}
